package com.oasys.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 密码工具类
 * @author mis_wu
 */
public final class PasswordUtils {

    private static final List<String> BASE_STR_LIST = Arrays.asList("1","2","3","4","5","6","7","8","9","0",
            "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
            "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");

    public static String hash(String password, String salt) {
        if (StringUtils.isBlank(password)) {
            return StringUtils.EMPTY;
        }
        salt = Objects.toString(salt, StringUtils.EMPTY);
        return DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
    }

    public static boolean check(String password, String hashText, String salt) {
        if (StringUtils.isAnyBlank(hashText, password)) {
            return false;
        }
        String hash = hash(password, salt);
        return Objects.equals(hashText, hash);
    }

    public static boolean strengthCheck(String password) {
        return true;
    }

    public static String rndSalt() {
        StringBuilder builder = new StringBuilder();
        ThreadLocalRandom rnd = ThreadLocalRandom.current();
        for (int i = rnd.nextInt(8, 16); i > 0; i--) {
            builder.append(BASE_STR_LIST.get(rnd.nextInt(0, BASE_STR_LIST.size() - 1)));
        }
        return builder.toString();
    }

    private PasswordUtils() {}

    public static void main(String[] args) {
        String admin = hash("admin", "222");
        String salt = rndSalt();
        System.out.println("密码盐值:"+salt);
    }

}
